package com.turing.selfwebservice.system;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.ws.Service;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import com.turing.post.webservice.client.CardHolderUser;
import com.turing.post.webservice.client.CommonWebResult;
import com.turing.post.webservice.client.IdType;
import com.turing.post.webservice.client.MerchantOper;
import com.turing.post.webservice.client.SelfWSLogonResult;
import com.turing.post.webservice.client.WebWscImpl;
import com.turing.post.webservice.client.WebWscImplPortType;
import com.turing.selfwebservice.util.Helper;
import com.turing.selfwebservice.util.ServletUtil;

public class LoginServlet extends DispatchAction {
	private HttpSession session = null;
	private WebWscImplPortType webWscImplPortType = null;

	/**
	 * 商户操作员登录
	 * 
	 */
	public ActionForward MerchantOperLogon(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		session = request.getSession();
		String _url = "logon";
		try {
			getLink();
			SessionHashTable sht = (SessionHashTable) session
					.getAttribute("SessionHashTable");
			webWscImplPortType = sht.getWebservice();
			String merchantNo = getParameter(request, "merchantNo");
			String mrchOperLogonName = getParameter(request,
					"mrchOperLogonName");
			String mrchOperPasswd = getParameter(request, "mrchOperPasswd");
			String usersafecode = getParameter(request, "verifyCode");
			String verifyCode = session.getAttribute("verifyCode").toString();
			if (null == usersafecode
					|| !usersafecode.equalsIgnoreCase(verifyCode)) {
				_url = "logon";
				request.setAttribute("errorMsg", "验证码输入错误");
				request.setAttribute("mrchOperLogonName", mrchOperLogonName);
				request.setAttribute("merchantNo", merchantNo);
				return mapping.findForward(_url);
			}
			MerchantOper merchantOper = new MerchantOper();
			merchantOper.setMerchantNo(merchantNo);
			merchantOper.setMrchOperLogonName(mrchOperLogonName);
			merchantOper.setMrchOperPasswd(mrchOperPasswd);
			SelfWSLogonResult logonResult = webWscImplPortType
					.merchantOperLogon(merchantOper);
			if (logonResult.isSuccess()) {
				_url = "success";
				MerchantOper oper = logonResult.getMerchantOper();
				session.setAttribute("userName", oper.getMrchOperName());
				session.setAttribute("MerchantOper", oper);
				session.setAttribute("organization", "商户操作员");
				session.setAttribute("userType", "MerchantOper");
			} else {
				_url = "logon";
				request.setAttribute("errorMsg", logonResult.getExcepMessage());
			}
		} catch (Exception e) {
			request.setAttribute("Error",
					"webservice连接异常，检查webservice是否启动或网络连通!");
			_url = "error";
		}
		return mapping.findForward(_url);
	}

	/**
	 * 注册用户登录
	 */
	public ActionForward CardHolderUserLogon(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		session = request.getSession();
		String _url = "logon";
		try {
			getLink();
			SessionHashTable sht = (SessionHashTable) session
					.getAttribute("SessionHashTable");
			webWscImplPortType = sht.getWebservice();
			String logonName = getParameter(request, "logonName");
			String logonPasswd = getParameter(request, "logonPasswd");
			String usersafecode = getParameter(request, "verifyCode");
			String verifyCode = session.getAttribute("verifyCode").toString();
			if (null == usersafecode
					|| !usersafecode.equalsIgnoreCase(verifyCode)) {
				_url = "logon";
				request.setAttribute("errorMsg", "验证码输入错误");
				request.setAttribute("logonName", logonName);
				return mapping.findForward(_url);
			}
			CardHolderUser cardHolderUser = new CardHolderUser();
			cardHolderUser.setLogonName(logonName);
			cardHolderUser.setLogonPasswd(logonPasswd);
			SelfWSLogonResult logonResult = webWscImplPortType
					.cardHolderUserLogon(cardHolderUser);
			if (logonResult.isSuccess()) {
				_url = "success";
				CardHolderUser holderUser = logonResult.getCardHolderUser();
				if (!ServletUtil.isEmpty(holderUser.getName())) {
					session.setAttribute("userName", holderUser.getName());
				} else {
					session.setAttribute("userName", holderUser.getLogonName());
				}
				session.setAttribute("CardHolderUser", holderUser);
				session.setAttribute("organization", "持卡用户");
				session.setAttribute("userType", "CardHolderUser");
			} else {
				_url = "logon";
				request.setAttribute("errorMsg", logonResult.getExcepMessage());
			}
		} catch (Exception e) {
			request.setAttribute("Error",
					"webservice连接异常，检查webservice是否启动或网络连通!");
			_url = "error";
		}
		return mapping.findForward(_url);
	}

	private void getLink() throws Exception {
		String wsdl = getDbConnection();
		if (!wsdl.equals("")) {
			URL wsdlURL = new URL(wsdl);
			QName serviceQName = new QName(
					"http://impl.webservice.post.turing.com/", "WebWscImpl");
			Service service = WebWscImpl.create(wsdlURL, serviceQName);
			WebWscImplPortType postPortType = service
					.getPort(WebWscImplPortType.class);
			SessionHashTable sht = new SessionHashTable();
			sht.setWebservice(postPortType);
			session.setAttribute("SessionHashTable", sht);
		}
	}

	/**
	 * @author BlackList
	 * @param 证件类型下拉框
	 */
	public ActionForward IdTypeList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		session = request.getSession();
		try {
			getLink();
			SessionHashTable sht = (SessionHashTable) session
					.getAttribute("SessionHashTable");
			webWscImplPortType = sht.getWebservice();
			List<IdType> list = webWscImplPortType
					.getIdTypeIdListByCategory("0");
			String s = Helper.JSON_List2String(list);
			response.getWriter().write(s);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}

	// 持卡用户找回密码
	/**
	 * @根据登录名检索返回用户信息，包含问题
	 * @param form
	 */
	public ActionForward CardUserDatilByUserName(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		session = request.getSession();
		try {
			getLink();
			SessionHashTable sht = (SessionHashTable) session
					.getAttribute("SessionHashTable");
			webWscImplPortType = sht.getWebservice();
			String username = request.getParameter("username");
			if (username != null) {
				CardHolderUser holderuser = webWscImplPortType
						.getCardHolderUserQuestionByLogonName(username);
				String s = Helper.JSON_Bean2String(holderuser);
				response.getWriter().write(s);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @找回密码
	 * @param form
	 */
	public ActionForward FindPasword(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			String username = request.getParameter("username");
			String newpassword = request.getParameter("newpassword");
			String answer1 = request.getParameter("answer1");
			String answer2 = request.getParameter("answer2");
			String answer3 = request.getParameter("answer3");

			CardHolderUser holderuser = new CardHolderUser();
			holderuser.setLogonName(username);
			holderuser.setLogonPasswd(newpassword);
			holderuser.setAnswer1(answer1);
			holderuser.setAnswer2(answer2);
			holderuser.setAnswer3(answer3);
			if (username != null) {
				CommonWebResult resultString = webWscImplPortType
						.getLossPasswordByCardHolderUser(holderuser);
				if (resultString.isSuccess() == true)
					response.getWriter().write("0");
				else
					response.getWriter().write(resultString.getExcepMessage());
			}
		} catch (Exception e) {
		}
		return null;
	}

	// 商户找回密码
	/**
	 * @填入商户名返回用户信息，包含问题
	 * @param form
	 */
	public ActionForward MerchantDatilByUserName(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		session = request.getSession();
		try {
			getLink();
			SessionHashTable sht = (SessionHashTable) session
					.getAttribute("SessionHashTable");
			webWscImplPortType = sht.getWebservice();
			String merchantusername = request.getParameter("merchantusername");
			if (merchantusername != null) {
				MerchantOper oper = webWscImplPortType
						.getMerchantOperQuestionByMrchOperLogonName(merchantusername);
				String s = Helper.JSON_Bean2String(oper);
				response.getWriter().write(s);
			}
		} catch (Exception e) {
		}
		return null;
	}

	/**
	 * @找回密码
	 * @param form
	 */
	public ActionForward MerchantFindPasword(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		try {
			String merchantusername = request.getParameter("merchantusername");
			String merchantnewpassword = request
					.getParameter("merchantnewpassword");
			String merchantanswer1 = request.getParameter("merchantanswer1");
			String merchantanswer2 = request.getParameter("merchantanswer2");
			String merchantanswer3 = request.getParameter("merchantanswer3");
			MerchantOper merchantoper = new MerchantOper();
			merchantoper.setMrchOperLogonName(merchantusername);

			merchantoper.setMrchOperPasswd(merchantnewpassword);
			merchantoper.setAnswer1(merchantanswer1);
			merchantoper.setAnswer2(merchantanswer2);
			merchantoper.setAnswer3(merchantanswer3);
			if (merchantusername != null) {
				CommonWebResult resultString = webWscImplPortType
						.getLossPasswordByMerchantOper(merchantoper);
				if (resultString.isSuccess() == true)
					response.getWriter().write("0");
				else
					response.getWriter().write(resultString.getExcepMessage());
			}
		} catch (Exception e) {
		}
		return null;
	}

	/**
	 * 读取连接数据库配置文件
	 * 
	 * @return string
	 * @throws Exception
	 */
//	private String getDbConnection() throws Exception {
//		String configPath = Thread.currentThread().getContextClassLoader()
//				.getResource("/").getPath();
//		String connStr = "";
//		File f = new File(configPath + "/DbConnection.xml");
//		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//		DocumentBuilder builder = factory.newDocumentBuilder();
//		Document doc = builder.parse(f);
//		NodeList nl = doc.getElementsByTagName("VALUE");
//		for (int i = 0; i < nl.getLength(); i++) {
//			connStr = doc.getElementsByTagName("connStr").item(i)
//					.getFirstChild().getNodeValue();
//		}
//		return connStr;
//	}
//	
	private String getDbConnection() {
		InputStream is = getServlet().getServletContext().getResourceAsStream(
				"/WEB-INF/WSConn.properties");
		Properties props = new Properties();
		try {
			props.load(is);
		} catch (IOException e) {
			System.err.println("DbConnection.xml File Is Not Find!");
		}
		String res = props.getProperty("webserver_address");
		return res;
	}
	
	protected String getParameter(HttpServletRequest request, String value)
			throws Exception {
		String val = request.getParameter(value);
		if (StringUtils.isBlank(val)) {
			return null;
		}
		return val.trim();
	}
}
